<template>
    <div class="dining-feedback">
        <!-- 提交需求表单 -->
        <el-form :model="feedbackForm" ref="feedbackFormRef" label-width="100px" class="feedback-form">
            <el-form-item label="需求内容" prop="content" :rules="[{ required: true, message: '请输入需求内容', trigger: 'blur' }]">
                <el-input
                    type="textarea"
                    v-model="feedbackForm.content"
                    :rows="4"
                    placeholder="请详细描述您的餐饮需求"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitFeedback">提交需求</el-button>
            </el-form-item>
        </el-form>

        <!-- 需求列表 -->
        <div class="feedback-list">
            <h3>我的需求记录</h3>
            <el-table :data="feedbackList" v-loading="loading">
                <el-table-column prop="content" label="需求内容" show-overflow-tooltip/>
                <el-table-column label="提交时间" width="180">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
                            {{ scope.row.status === 0 ? '待回复' : '已回复' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="管理员回复" show-overflow-tooltip>
                    <template #default="scope">
                        <span :class="{ 'no-reply': !scope.row.adminReply }">
                            {{ scope.row.adminReply || '暂无回复' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="回复时间" width="180">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.replyTime) }}
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '../../../utils/axios'

const loading = ref(false)
const feedbackFormRef = ref(null)

// 获取当前用户ID
const getCurrentUserId = () => {
    try {
        const userStr = localStorage.getItem('user')
        if (!userStr) {
            console.warn('未找到用户信息')
            return null
        }
        const user = JSON.parse(userStr)
        if (!user || !user.id) {
            console.warn('用户信息不完整:', user)
            return null
        }
        return user.id
    } catch (error) {
        console.error('获取用户信息失败:', error)
        return null
    }
}

const feedbackForm = ref({
    content: '',
    userId: getCurrentUserId()
})
const feedbackList = ref([])

// 提交需求
const submitFeedback = async () => {
    const userId = getCurrentUserId()
    if (!userId) {
        ElMessage.warning('请先登录后再提交需求')
        return
    }

    if (!feedbackForm.value.content.trim()) {
        ElMessage.warning('请输入需求内容')
        return
    }

    try {
        await feedbackFormRef.value.validate()
        console.log('提交需求数据:', {
            content: feedbackForm.value.content,
            userId: userId,
            status: 0
        })
        
        const response = await axios.post('/dining/feedback', {
            content: feedbackForm.value.content,
            userId: userId,
            status: 0
        })

        if (response.data.code === 200) {
            ElMessage.success('需求提交成功')
            feedbackForm.value.content = ''
            await getFeedbackList()
        } else {
            throw new Error(response.data.message || '提交失败')
        }
    } catch (error) {
        console.error('提交需求失败:', error)
        ElMessage.error('提交需求失败：' + (error.message || '未知错误'))
    }
}

// 获取需求列表
const getFeedbackList = async () => {
    const userId = getCurrentUserId()
    if (!userId) {
        ElMessage.warning('请先登录后再查看需求列表')
        return
    }

    loading.value = true
    try {
        console.log('获取需求列表，用户ID:', userId)
        const response = await axios.get('/dining/feedback/user', {
            params: {
                userId: userId
            }
        })
        
        console.log('需求列表原始数据:', response.data)
        
        if (response.data.code === 200) {
            // 处理返回的数据，确保字段名称正确
            feedbackList.value = (response.data.result || []).map(item => {
                console.log('处理需求项:', item)
                const processedItem = {
                    ...item,
                    content: item.content || '',
                    createTime: item.createTime || item.create_time || '',
                    status: typeof item.status === 'number' ? item.status : 0,
                    adminReply: item.reply || item.adminReply || item.admin_reply || '',
                    replyTime: item.replyTime || item.reply_time || null
                }
                console.log('处理后的需求项:', processedItem)
                return processedItem
            })
            console.log('获取到的需求列表:', feedbackList.value)
        } else if (response.data.code === 404) {
            console.log('暂无需求数据')
            feedbackList.value = []
        } else {
            throw new Error(response.data.message || '获取需求列表失败')
        }
    } catch (error) {
        if (error.response && error.response.status === 404) {
            console.log('暂无需求数据')
            feedbackList.value = []
        } else {
            console.error('获取需求列表失败:', error)
            ElMessage.error('获取需求列表失败：' + (error.message || '未知错误'))
            feedbackList.value = []
        }
    } finally {
        loading.value = false
    }
}

// 格式化时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return '-'
    try {
        const date = new Date(dateTime)
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        })
    } catch (error) {
        console.error('时间格式化失败:', error)
        return dateTime
    }
}

onMounted(async () => {
    const userId = getCurrentUserId()
    if (userId) {
        await getFeedbackList()
    } else {
        console.warn('用户未登录，无法获取需求列表')
    }
})
</script>

<style scoped>
.dining-feedback {
    padding: 20px;
}

.feedback-form {
    max-width: 600px;
    margin: 0 auto 40px;
}

.feedback-list {
    margin-top: 30px;
}

.feedback-list h3 {
    margin-bottom: 20px;
    color: #606266;
}

.no-reply {
    color: #909399;
    font-style: italic;
}

.el-table {
    margin-top: 20px;
}

.el-table .cell {
    word-break: break-word;
}
</style> 